<!--
 * @author guojiteng
 新建/编辑闯关
 -->
<template>
  <div class="a-rush-manage">
    <div class="a-rush-manage-title">新建/编辑闯关</div>
    <section v-loading="loading" class="a-rush-manage-main">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" class="form">
        <el-form-item label="闯关名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入闯关名称" maxlength="50" />
        </el-form-item>
        <el-form-item label="闯关分类" prop="classifyId">
          <el-cascader
            v-if="showClassify"
            ref="classify"
            v-model="form.classifyId"
            :options="classifyOptions"
            style="width: 100%"
            clearable
            :props="classifyProps"
          />
        </el-form-item>

        <el-form-item label="排行榜样式" prop="rankingListStyle">
          <el-select v-model="form.rankingListStyle">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <section v-if="form.rankingListStyle === '0'" class="rankImg">
          <div class="demo-image__preview">
            <el-image
              style="width: 100px; height: 100px"
              :src="require('../../special/images/rankA.jpg')"
              :preview-src-list="[require('../../special/images/rankA.jpg')]"
            />
          </div>
        </section>
        <section v-if="form.rankingListStyle === '1'" class="rankImg">
          <div class="demo-image__preview">
            <el-image
              style="width: 100px; height: 100px"
              :src="require('../../special/images/rankB.jpg')"
              :preview-src-list="[require('../../special/images/rankB.jpg')]"
            />
          </div>
        </section>
        <el-form-item label="积分配置" prop="passPointsRule">
          <el-radio-group v-model="form.passPointsRule">
            <el-radio :label="0">每日每关可重复获得积分</el-radio>
            <el-radio :label="1">每日每关可得一次积分</el-radio>
            <el-radio :label="2">每关可得一次积分</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="闯关图片" prop="imgId">
          <image-upload
            :key="upload.imagecropperKey"
            v-model="form.imgId"
            :preview-id="upload.viewId"
            :forever="true"
            :width="330"
            :view="upload.view"
            :height="140"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
            :is-oss="upload.isOss"
            @crop-success="picSuccess"
            @changeOssPath="
              (path) => {
                upload.viewId = path
              }
            "
          />
          <p style="margin-bottom: 20px" />
        </el-form-item>
        <el-form-item label="排行榜背景图">
          <image-upload
            :key="upload2.imagecropperKey"
            v-model="form.rankingListImgId"
            :preview-id="upload2.viewId"
            :forever="true"
            :width="750"
            :view="upload.view"
            :height="316"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
            :is-oss="upload.isOss"
            @changeOssPath="
              (path) => {
                upload2.viewId = path
              }
            "
          />
          <p style="margin-bottom: 20px" />
        </el-form-item>
        <el-form-item label="个人排名背景">
          <image-upload
            :key="upload3.imagecropperKey"
            v-model="form.rankingListBgColor"
            :preview-id="upload3.viewId"
            :forever="true"
            :width="702"
            :view="upload.view"
            :height="120"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
            :is-oss="upload.isOss"
            @changeOssPath="
              (path) => {
                upload3.viewId = path
              }
            "
          />
          <p style="margin-bottom: 20px" />
        </el-form-item>
        <el-form-item label="是否实名认证">
          <el-radio-group v-model="form.isCertification">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排行类型">
          <el-select v-model="form.rankingType" placeholder="请选择排行类型" style="width: 100%;">
            <el-option :key="1" value="1" label="总成绩排行" />
            <el-option :key="2" value="2" label="单次最高分排行" />
          </el-select>
        </el-form-item>
        <el-form-item label="排行榜展示数量" prop="rankLimitNum">
          <el-input v-model.number="form.rankLimitNum" oninput="value=value.replace(/[^0-9-]/g,'')" placeholder="请输入" :maxlength="5" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="form.sort" placeholder="请输入排序号（值越大，越靠前）" :maxlength="5" show-word-limit/>
          <!-- <el-input-number v-model="form.sort" :min="1" :max="9999" label="请输入排序号（值越大，越靠前）" :step="1" step-strictly></el-input-number> -->
        </el-form-item>
      </el-form>
    </section>

    <section class="a-rush-manage-footer">
      <el-button style="padding: 10px 30px" @click="onCancel">取 消</el-button>
      <el-button type="primary" @click="onSubmint('form')">确 定</el-button>
    </section>
    <!--  选择题库  -->
    <el-dialog v-el-drag-dialog title="选择题库" :visible.sync="dialogPowerVisible" center width="450px" :close-on-click-modal="false">
      <choose-qs v-if="dialogPowerVisible":is-selsct="true"   ref="PowerTreeFun" :checked-data="form.quesBankClassifyIds" @subQs="getQsFun" @dialogPower="dialogPower" />
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px" @click="dialogPowerVisible = false">取消</el-button>
        <el-button style="padding: 8px 30px" type="primary" @click="powerTreeFun">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { specialText, number, doublescore, intwith } from '@/utils/validate'
import { mapGetters } from 'vuex'
import ImageUpload from '@/components/ImageUpload'
import ChooseQs from '@/views/skill/answerRush/components/chooseQs'
import elDragDialog from '@/directive/el-drag-dialog'
import { getClassifyTree, insert, update, get } from './../api/rush'
import { queryPage } from '@/views/skill/answerRush/api/template'

export default {
  name: 'RushManage',
  components: { ImageUpload, ChooseQs },
  directives: { elDragDialog },
  data() {
    return {
      dialogPowerVisible: false,
      qsName: [],
      qsId: [],
      options: [], // 闯关策略模板
      loading: false,
      options: [
        {
          value: '0',
          label: '排行榜样式一'
        },
        {
          value: '1',
          label: '排行榜样式二'
        }
      ],
      form: {
        id: '',
        name: '',
        passPointsRule: 0,
        rankingListStyle: '0',
        imgId: '',
        rankingListImgId: '',
        rankingListBgColor: '',
        classifyId: '',
        rankingType: '',
        rankLimitNum: '',
        isCertification: 0,
        sort: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入闯关名称', trigger: 'blur' },
          { validator: specialText, trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '长度在 1 到 50 个字符',
            trigger: 'blur'
          }
        ],
        classifyId: [{ required: true, message: '请选择分类', trigger: 'change' }],
        rankingListStyle: [{ required: true, message: '请选择排行榜分类', trigger: 'change' }],
        passPointsRule: [{ required: true, message: '请选择积分规则', trigger: 'change' }],
        sort: [{ required: true, message: '请选择排序', trigger: 'change' }, { validator: number, trigger: 'blur' }],
        imgId: [{ required: true, message: '请选择闯关图片', trigger: 'change' }]
      },
      upload: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0,
        isOss: sessionStorage.getItem('FILE_SAVE_THIRD_CONFIG') || false
      },
      upload2: {
        viewId: '',
        imagecropperKey: 1
      },
      upload3: {
        viewId: '',
        imagecropperKey: 2
      },
      classifyProps: {
        label: 'classifyName',
        value: 'id',
        checkStrictly: true
      },
      classifyOptions: [],
      showClassify: false,
      state: 'create',
      t: '0',
      type: 1
    }
  },
  computed: {
    ...mapGetters(['user'])
  },
  watch: {
    'form.classifyId': {
      handler(newName, oldName) {
        if (this.$refs.classify) {
          this.$refs.classify.dropDownVisible = false
        }
      },
      immediate: true,
      deep: true
    }
  },
  async created() {
    this.state = this.$route.query.type === 'c' ? 'create' : 'update'
    await this.getClassify()
    if (this.$route.query.type === 'u') {
      if (this.$route.query.i) {
        this.getData(this.$route.query.i)
      } else {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.$router.back()
          }
        })
      }
    } else {
      this.showClassify = true
    }
  },

  methods: {
    /**
     * 上传成功后重新校验
     * */
    picSuccess() {
      setTimeout(() => {
        this.$refs['form'].validateField('imgId', (val) => {
          if (!val) {
            return true
          } else {
            return false
          }
        })
      }, 1500)
    },
    /**
     * 去掉某个题库
     * */
    handleClose(i) {
      this.form.quesBankClassifyIds.splice(i, 1)
      this.qsName.splice(i, 1)
    },
    /**
     * 获取闯关策略模板
     * */
    getList() {
      var query = {
        page: 1,
        pageSize: 9999
      }
      return new Promise((resolve, reject) => {
        queryPage(query)
          .then((response) => {
            this.options = response.data.data.rows || []
          })
          .catch((error) => {
            reject(error)
            this.listLoading = false
          })
      })
    },
    /**
     * 题库
     */
    getQsFun(obj) {
      this.qsName = obj.menuName
      this.form.quesBankClassifyIds = obj.menuIds
      this.$refs['form'].validateField('quesBankClassifyIds', (val) => {
        if (!val) {
          return true
        } else {
          return false
        }
      })
    },
    /**
     * 关闭权限弹框
     */
    dialogPower(val) {
      this.dialogPowerVisible = val
    },
    /**
     * 确认题库
     */
    powerTreeFun() {
      this.$refs.PowerTreeFun.saveData()
      this.dialogPowerVisible = false
    },
    /**
     * 获取分类
     */
    getClassify() {
      return new Promise((resolve, reject) => {
        getClassifyTree({ classifyType: 'JNZQFL04' })
          .then(({ data }) => {
            this.classifyOptions = data.data || []
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    /**
     * 根编辑回显
     */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({ id: id })
          .then((res) => {
            loading.close()
            const data = res.data.data
            for (const key in this.form) {
              if (key === 'imgId') {
                this.form[key] = data.imgId
                this.upload.viewId = data.imgIdUrl
              } else if (key === 'rankingListImgId') {
                this.form[key] = data.rankingListImgId
                this.upload2.viewId = data.rankingListImgIdUrl
              } else if (key === 'rankingListBgColor') {
                this.form[key] = data.rankingListBgColor
                this.upload3.viewId = data.rankingListBgColorUrl
              } else if (key === 'classifyId') {
                const classifyIdList = data.classifyId.split(',')
                this.form[key] = classifyIdList
              } else {
                this.form[key] = data[key]
              }
            }
            this.$nextTick(() => {
              this.showClassify = true
            })
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    },

    /**
     * 取消闯关维护
     */
    onCancel() {
      this.$router.push({
        path: this.$filterPath('index'),
        query: { t: this.t }
      })
    },

    /**
     * 发布闯关
     */
    onSubmint() {
      for (let i = 0; i < this.form.classifyId.length; i++) {
        console.log('@@@@@', this.form.classifyId[i])
      }
      console.log('----', this.form.classifyId)
      if (this.state === 'create') {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const {
              id,
              name,
              passPointsRule,
              imgId,
              rankingListImgId,
              rankingListBgColor,
              classifyId,
              rankingType,
              rankLimitNum,
              isCertification,
              sort,
              rankingListStyle
            } = this.form

            return new Promise((resolve, reject) => {
              insert({
                id,
                name,
                passPointsRule,
                imgId,
                rankingListImgId,
                rankingListBgColor,
                rankingType,
                rankLimitNum,
                isCertification,
                sort,
                rankingListStyle,
                classifyId: this.form.classifyId.length > 0 ? this.form.classifyId[this.form.classifyId.length - 1] : ''
              })
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$router.push({ path: this.$filterPath('index') })
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const {
              id,
              name,
              passPointsRule,
              imgId,
              rankingListImgId,
              rankingListBgColor,
              classifyId,
              rankingType,
              rankLimitNum,
              isCertification,
              sort,
              rankingListStyle
            } = this.form
            return new Promise((resolve, reject) => {
              update({
                id,
                name,
                passPointsRule,
                imgId,
                rankingListImgId,
                rankingListBgColor,
                rankingType,
                rankLimitNum,
                isCertification,
                sort,
                rankingListStyle,
                classifyId: this.form.classifyId.length > 0 ? this.form.classifyId[this.form.classifyId.length - 1] : ''
              })
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '编辑成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$router.push({ path: this.$filterPath('index') })
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            return false
          }
        })
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">
.a-rush-manage {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;

  .a-rush-manage-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;

    &:before {
      content: '';
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .a-rush-manage-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;

    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }

    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }

    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }

    &:hover {
      overflow: auto;
    }

    .form {
      width: 1000px !important;
      margin: 0 auto;

      .el-select {
        width: 100%;
      }
      .rankImg {
        width: 100px;
        height: 100px;
        margin-left: 150px;
        margin-bottom: 20px;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .line {
        text-align: center;
      }
    }

    .select-data {
      display: inline-block;
      background: rgba(246, 246, 246, 1);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: rgba(51, 51, 51, 1);
      padding: 0 10px;
      margin-right: 5px;
      margin-bottom: 8px;

      i {
        cursor: pointer;
        padding-left: 5px;
      }
    }

    .selectbtn {
      display: inline-block;
      width: 120px;
      background: rgba(255, 255, 255, 1);
      @include border-color(1px, dotted, $mainColor);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      @include font-color($mainColor);
      text-align: center;
      cursor: pointer;
    }
  }

  .a-rush-manage-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }
}
</style>
<style lang="scss">
.a-rush-manage {
  .classify-tree-con {
    position: relative;
    height: 400px;
    overflow: hidden;

    .classify-tree-con-scrollbar {
      overflow: hidden;

      .el-scrollbar__wrap {
        max-height: 381px;
      }
    }

    .custom-tree-node {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      width: 100%;

      .tree-node-txt {
        flex: 1;
      }
    }
  }
}
</style>
